#!/usr/bin/env python
# -*- coding: utf-8 -*-

import time
import telnetlib

"""
netstream类，用于进行telnet的判断
"""

class nsbase():
    def __init__(self, ip='127.0.0.1', port=8002):
        self.tl = telnetlib.Telnet(ip, port)
        self.twait = 0.1
        self.send('\n')
        self.tl.read_very_eager()

    def close(self):
        self.tl.close()

    def send(self, s):
        self.tl.write(s.encode('ascii'))
        time.sleep(self.twait)

    def set(self, name, value):
        self.send("%s=%s"%(name, value))

    def get(self, name, pyname=None):
        """
         @brief 从lua中获得变量
        """
        pyname = pyname or name
        cmd = "print('%s='..%s)"%(pyname, name)
        self.send(cmd)
        time.sleep(self.twait)
        ret = self.tl.read_very_eager().decode('ascii')
        exec("global %s; %s"%(pyname, ret))
        return ret

if __name__ == '__main__':
    n = nsbase()
    a=2
    n.set("a", 1)
    n.get("a")
    if a==1 :
        print('OK')
    else:
        print('Not OK')
    n.close()
